package com.csc.banking.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class CustomEntityManager implements ServletContextListener {
//	protected EntityManager entityManager;
//
//	public EntityManager getEntityManager() {
//		return entityManager;
//	}
//
//	@PersistenceContext
//	public void setEntityManager(EntityManager entityManager) {
//		this.entityManager = entityManager;
//
//	}
	private static EntityManagerFactory emf;

	 public static EntityManager createEntityManager() {
	        if (emf == null) {
	            throw new IllegalStateException("Context is not initialized yet.");
	        }

	        return emf.createEntityManager();
	    }

		public void contextDestroyed(ServletContextEvent arg0) {
			// Destroys entity manager factory
			emf.close();
		}

		public void contextInitialized(ServletContextEvent arg0) {
			// Creates entity manager factory
			 emf = Persistence.createEntityManagerFactory("banking");
		}
}
